const { Op } = require('sequelize')
const sequelize = require('../config/database')
const User = require('../models/user')
const Department = require('../models/department')
const UserPermission = require('../models/userPermission')
const PermissionService = require('../services/permissionService')
const logger = require('../utils/logger')
const bcrypt = require('bcryptjs')

// 获取用户列表
exports.getList = async (req, res) => {
  try {
    logger.info('开始获取用户列表, 参数:', req.query)
    const { page = 1, limit = 20, keyword = '', status = '', departmentId = '' } = req.query
    
    // 构建查询条件
    const where = {}
    if (keyword) {
      where[Op.or] = [
        { username: { [Op.like]: `%${keyword}%` } },
        { name: { [Op.like]: `%${keyword}%` } },
        { phone: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } }
      ]
    }
    if (status !== '') {
      where.status = parseInt(status)
    }

    logger.info('查询条件:', where)
    
    // 构建部门关联条件
    const includeOptions = [{
      model: Department,
      as: 'departments',
      attributes: ['id', 'name'],
      through: { attributes: [] }
    }]

    if (departmentId) {
      includeOptions[0].where = { id: departmentId }
    }

    logger.info('开始执行查询')
    
    // 查询用户列表
    const { count, rows } = await User.findAndCountAll({
      where,
      attributes: [
        'id', 'username', 'name', 'phone', 'email', 'status',
        'role_id', 'primary_department_id', 'createdAt', 'updatedAt'
      ],
      include: includeOptions,
      distinct: true,
      offset: (parseInt(page) - 1) * parseInt(limit),
      limit: parseInt(limit),
      order: [['createdAt', 'DESC']]
    })

    logger.info(`查询完成，总数: ${count}, 当前页数据量: ${rows.length}`)

    // 处理返回数据
    const items = rows.map(user => {
      const plainUser = user.get({ plain: true })
      return {
        ...plainUser,
        role_id: plainUser.role_id || 'normal_user'
      }
    })

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        total: count,
        items: items
      }
    })
  } catch (error) {
    logger.error('获取用户列表失败:', {
      message: error.message,
      stack: error.stack,
      query: req.query
    })
    res.status(500).json({
      code: 500,
      message: `获取用户列表失败: ${error.message}`
    })
  }
}

// 创建用户
exports.create = async (req, res) => {
  try {
    const { username, name, phone, email, departmentIds, status = 1 } = req.body

    // 检查用户名是否已存在
    const existingUser = await User.findOne({ where: { username } })
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: '用户名已存在'
      })
    }

    // 创建用户
    const user = await User.create({
      username,
      name,
      phone,
      email,
      password: bcrypt.hashSync('123456', 10), // 默认密码
      status
    })

    // 关联部门
    if (departmentIds && departmentIds.length > 0) {
      await user.setDepartments(departmentIds)
    }

    res.json({
      code: 200,
      message: '创建成功',
      data: user
    })
  } catch (error) {
    logger.error('创建用户失败:', error)
    res.status(500).json({
      code: 500,
      message: '创建用户失败'
    })
  }
}

// 更新用户
exports.update = async (req, res) => {
  try {
    const { id } = req.params
    const { name, phone, email, departmentIds, status, role_id, primary_department_id } = req.body

    logger.info('更新用户请求参数:', { id, ...req.body })

    // 查找用户
    const user = await User.findByPk(id)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      })
    }

    // 如果是设置为部门管理员，检查主部门是否存在
    if (role_id === 'dept_admin' && !primary_department_id) {
      return res.status(400).json({
        code: 400,
        message: '部门管理员必须设置主部门'
      })
    }

    // 更新用户信息
    const updateData = {
      name,
      phone,
      email,
      status,
      role_id,
      primary_department_id: role_id === 'dept_admin' ? primary_department_id : null
    }

    logger.info('更新用户数据:', updateData)
    await user.update(updateData)

    // 更新部门关联
    if (departmentIds) {
      await user.setDepartments(departmentIds)
    }

    // 清除用户权限缓存
    await PermissionService.clearPermissionCache(id)

    res.json({
      code: 200,
      message: '更新成功'
    })
  } catch (error) {
    logger.error('更新用户失败:', { 
      message: error.message, 
      stack: error.stack,
      params: req.body 
    })
    res.status(500).json({
      code: 500,
      message: `更新用户失败: ${error.message}`
    })
  }
}

// 删除用户
exports.delete = async (req, res) => {
  try {
    const { id } = req.params

    // 查找用户
    const user = await User.findByPk(id)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      })
    }

    // 开启事务
    const t = await sequelize.transaction()

    try {
      // 先删除用户权限
      await UserPermission.destroy({
        where: { user_id: id },
        transaction: t
      })

      // 删除用户
      await user.destroy({ transaction: t })

      // 提交事务
      await t.commit()

      res.json({
        code: 200,
        message: '删除成功'
      })
    } catch (error) {
      // 回滚事务
      await t.rollback()
      throw error
    }
  } catch (error) {
    logger.error('删除用户失败:', error)
    res.status(500).json({
      code: 500,
      message: '删除用户失败'
    })
  }
}

// 更改用户状态
exports.updateStatus = async (req, res) => {
  try {
    const { id } = req.params
    const { status } = req.body

    // 查找用户
    const user = await User.findByPk(id)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      })
    }

    // 更新状态
    await user.update({ status })

    res.json({
      code: 200,
      message: '状态更新成功'
    })
  } catch (error) {
    logger.error('更新用户状态失败:', error)
    res.status(500).json({
      code: 500,
      message: '更新用户状态失败'
    })
  }
}

// 重置用户密码
exports.resetPassword = async (req, res) => {
  try {
    const { id } = req.params

    // 查找用户
    const user = await User.findByPk(id)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      })
    }

    // 重置密码为 123456
    await user.update({
      password: bcrypt.hashSync('123456', 10)
    })

    res.json({
      code: 200,
      message: '密码重置成功'
    })
  } catch (error) {
    logger.error('重置用户密码失败:', error)
    res.status(500).json({
      code: 500,
      message: '重置用户密码失败'
    })
  }
}

// 批量删除用户
exports.batchDelete = async (req, res) => {
  try {
    const { ids } = req.body
    if (!ids || !Array.isArray(ids) || !ids.length) {
      return res.status(400).json({
        code: 400,
        message: '请选择要删除的用户'
      })
    }

    // 开启事务
    const t = await sequelize.transaction()

    try {
      // 先删除用户权限
      await UserPermission.destroy({
        where: {
          user_id: {
            [Op.in]: ids
          }
        },
        transaction: t
      })

      // 删除用户
      await User.destroy({
        where: {
          id: ids
        },
        transaction: t
      })

      // 提交事务
      await t.commit()

      res.json({
        code: 200,
        message: '批量删除成功'
      })
    } catch (error) {
      // 回滚事务
      await t.rollback()
      throw error
    }
  } catch (error) {
    logger.error('批量删除用户失败:', error)
    res.status(500).json({
      code: 500,
      message: '批量删除用户失败'
    })
  }
}

// 批量更新用户状态
exports.batchUpdateStatus = async (req, res) => {
  try {
    logger.info('开始批量更新用户状态, 请求体:', req.body)
    logger.info('请求头:', req.headers)
    logger.info('请求URL:', req.originalUrl)
    logger.info('请求方法:', req.method)
    
    const { ids, status } = req.body
    if (!ids || !Array.isArray(ids) || !ids.length) {
      logger.warn('无效的用户ID列表:', ids)
      return res.status(400).json({
        code: 400,
        message: '请选择要更新状态的用户'
      })
    }

    if (![0, 1, 2].includes(parseInt(status))) {
      logger.warn('无效的状态值:', status)
      return res.status(400).json({
        code: 400,
        message: '无效的状态值'
      })
    }

    logger.info('开始更新用户状态, ids:', ids, 'status:', status)
    // 更新用户状态
    await User.update(
      { status: parseInt(status) },
      {
        where: {
          id: {
            [Op.in]: ids
          }
        }
      }
    )

    logger.info('批量更新用户状态成功')
    res.json({
      code: 200,
      message: '批量状态更新成功'
    })
  } catch (error) {
    logger.error('批量更新用户状态失败:', { 
      message: error.message, 
      stack: error.stack, 
      body: req.body,
      headers: req.headers,
      url: req.originalUrl,
      method: req.method
    })
    res.status(500).json({
      code: 500,
      message: '批量更新用户状态失败'
    })
  }
}

// 批量调整部门
exports.batchUpdateDepartment = async (req, res) => {
  try {
    const { userIds, departmentIds } = req.body
    
    if (!userIds || !Array.isArray(userIds) || !userIds.length) {
      return res.status(400).json({
        code: 400,
        message: '请选择要调整部门的用户'
      })
    }

    if (!departmentIds || !Array.isArray(departmentIds)) {
      return res.status(400).json({
        code: 400,
        message: '请选择部门'
      })
    }

    // 查找所有用户
    const users = await User.findAll({
      where: {
        id: userIds
      }
    })

    // 批量更新用户部门
    for (const user of users) {
      await user.setDepartments(departmentIds)
      // 清除用户权限缓存
      await PermissionService.clearPermissionCache(user.id)
    }

    res.json({
      code: 200,
      message: '批量调整部门成功'
    })
  } catch (error) {
    logger.error('批量调整部门失败:', error)
    res.status(500).json({
      code: 500,
      message: '批量调整部门失败'
    })
  }
}

// 设置用户个人权限
exports.setUserPermissions = async (req, res) => {
  try {
    const { id } = req.params
    const { permissions } = req.body

    // 查找用户
    const user = await User.findByPk(id)
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      })
    }

    // 更新或创建用户权限
    await UserPermission.upsert({
      user_id: id,
      permissions
    })

    // 清除用户权限缓存
    await PermissionService.clearPermissionCache(id)

    res.json({
      code: 200,
      message: '权限设置成功'
    })
  } catch (error) {
    logger.error('设置用户权限失败:', error)
    res.status(500).json({
      code: 500,
      message: '设置用户权限失败'
    })
  }
} 